﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.ObjectBuilder2;

namespace WDA.Core
{
	/// <summary>
	/// A service controller for locally hosted services.
	/// </summary>
	public class LocalServiceController : IServiceController, IBuilderAware
	{
		private bool _disposed;
		private ManagedInstanceProvider _instanceProvider;
      private readonly Type _contractType;
      private readonly string _serviceName;

		/// <summary>
		/// Main general-purpose runtime-level container.
		/// </summary>
      [Dependency]
      public IUnityContainer Container { get; set; }

		/// <summary>
		/// Creates new instance of local service controller.
		/// </summary>
		/// <param name="contractType">CLR type of service contract.</param>
		/// <param name="serviceName">WDAB service name.</param>
		/// <param name="behavior">Object desribing service behavior (not used currently).</param>
		public LocalServiceController(Type contractType, string serviceName, ServiceBehaviorAttribute behavior)
		{
         _contractType = contractType;
         _serviceName = serviceName;
		}
      
		#region IServiceController Members
      /// <summary>
      /// Creates new service implementation instance using <see cref="ManagedInstanceProvider"/>.
      /// </summary>
      /// <returns></returns>
		public object CreateServiceChannel()
		{
			return _instanceProvider.GetInstance(null);
		}
		#endregion

		#region IDisposable Members
		public void Dispose()
		{
			if (!_disposed)
			{
				Dispose(true);
				_disposed = true;			
			}
			GC.SuppressFinalize(this);
		}
		public virtual void Dispose(bool disposing)
		{
		}
		#endregion

      #region IBuilderAware Members
      public void OnBuiltUp(object buildKey)
      {
         _instanceProvider = Container.BuildUp(new ManagedInstanceProvider(_contractType, _serviceName));
      }
      public void OnTearingDown()
      {         
      }
      #endregion
   }
}
